import { Autowired } from 'j-spring';
import { Service, Transactional } from './SpringJpaAnnotation';
import { SpringDao } from './SpringRepository';
import { EntityOption, JpaEntity, JpaSearch } from './SpringJpaEntity';
import { convertToWhere, convertSearch } from './SpringJpaUtil';
import { Repository } from 'typeorm';
@Service()
export class SpringSearchDao {
  @Autowired()
  springDao: SpringDao;

  /**
   * 获取实体存储类模板
   */
  async getRepositoryBySearch(
    search: JpaSearch<any, any>
  ): Promise<Repository<any>> {
    const e = this.springDao.getEntityManager();
    return e.getRepository(search.entityTarget);
  }

  //获取id集合
  @Transactional()
  async getIds<T extends JpaEntity<T>>(
    search: JpaSearch<T, any>
  ): Promise<number[]> {
    const e = this.springDao.getEntityManager();
    const entityList = await e.find(search.entityTarget, {
      where: convertToWhere(search),
      select: ['id'],
    });
    return entityList.map(e => e.id);
  }

  //批量更新
  @Transactional()
  async batchUpdate<T extends JpaEntity<T>>(
    search: JpaSearch<T, any>,
    partEntity: EntityOption<T>
  ): Promise<number> {
    const r = await this.getRepositoryBySearch(search);
    const ids = await this.getIds(search);
    for (let id of ids) {
      await r.update({ id }, partEntity);
    }
    return ids.length;
  }

  //批量删除
  @Transactional()
  async batchRemove<T extends JpaEntity<T>>(
    search: JpaSearch<T, any>
  ): Promise<number> {
    const r = await this.getRepositoryBySearch(search);
    const ids = await this.getIds(search);
    for (let id of ids) {
      await r.delete(id);
    }
    return ids.length;
  }

  @Transactional()
  async find<T extends JpaEntity<T>>(search: JpaSearch<T, any>): Promise<T[]> {
    const searchParam = convertSearch(search);
    const e = this.springDao.getEntityManager();
    return e.find(search.entityTarget, searchParam);
  }
}
